<?php

use oneStep\Response;
use Symfony\Component\VarDumper\Cloner\VarCloner;
use Symfony\Component\VarDumper\Dumper\CliDumper;
use Symfony\Component\VarDumper\Dumper\HtmlDumper;

if (function_exists('json') === false) {
    function json($data)
    {
        Paraphrase($data);
        Response::$headerInfo = 'Content-type: application/json';
        return json_encode($data);
    }
}

function config()
{
    $data = require(ROOTPATH . '/App/Config/db.php');
    return $data;
}

function view($tpmPath, $restful = [])
{
    Paraphrase($restful);
    Response::$headerInfo = 'text/html; charset=UTF-8';
    ob_start();
    require(ROOTPATH . '/App/Tem/' . $tpmPath . '.html');
    $data = ob_get_contents();
    ob_end_clean();
    return $data;
}

function Paraphrase(&$restful)
{
    if (!is_array($restful)) {
        return false;
    }

    foreach ($restful as $key => &$val) {
        if (is_array($val)) {
            Paraphrase($val);
        } else {
            $val = htmlspecialchars($val);
        }
    }
}

/**
 * @return array
 */
function getHeaders()
{
    $headers = array();

    foreach ($_SERVER as $key => $value) {
        if (substr($key, 0, 5) === 'HTTP_') {
            $key           = substr($key, 5);
            $key           = str_replace('_', ' ', $key);
            $key           = str_replace(' ', '-', $key);
            $key           = strtolower($key);
            $headers[$key] = $value;
        }
    }
    return $headers;
}

/**
 * @param array $data
 */
function dd(...$args)
{
    foreach ($args as $x) {
        d($x);
    }
    die(1);
}

function d($value)
{
    if (class_exists(CliDumper::class)) {
        $dumper = 'cli' === PHP_SAPI ? new CliDumper : new HtmlDumper;
        $dumper->dump((new VarCloner)->cloneVar($value));
    } else {
        var_dump($value);
    }
}

function randomNums($min, $max, $num, $re = false)
{
    $arr = array();
    $t   = 0;
    $i   = 0;
    // 如果数字不可重复，防止无限死循环
    if (!$re) {
        $num = min($num, $max - $min + 1);
    }
    do {
        // 取随机数

        $t = mt_rand($min, $max);

        if (!$re && isset($arr[$t])) {
            // 数字重复

            continue;
        }
        $arr[$t] = $t;

        ++$i;
    } while ($i < $num);

    return $arr;
}

/**
 * @param $data
 * @param $key
 * @param string $method
 * @param int $options
 * @return false|string
 */
function encrypt($data, $key, $method = 'DES-ECB', $options = 0)
{
    return openssl_encrypt($data, $method, $key, $options);
}

/**
 * @param $data
 * @param $key
 * @param string $method
 * @param int $options
 * @return false|string
 */
function decrypt($data, $key, $method = 'DES-ECB', $options = 0)
{
    return openssl_decrypt($data, $method, $key, $options);
}

